import axios from "axios";
import { ElMessage } from "element-plus";
// 创建新的axios实例
const service = axios.create({
  // 环境变量，需要在.env文件中配置
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时时间暂定10s
  timeout: 10000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

// 在发送ajax请求之前，拦截并添加相应的参数
service.interceptors.request.use(
  (config) => {
    const token = window.sessionStorage.getItem("token");
    if (token != null) {
      config.headers.Authorization = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    // 发送之前失败了
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 请求成功之后，处理相应体
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.state != 200) {
      ElMessage({
        message: res.message,
        type: "error",
        showClose: true,
      });
    }
    return response;
  },
  // 发送错误时
  (error) => {
    ElMessage({
      message: error.message,
      type: "error",
      showClose: true,
    });
    return Promise.reject(error);
  }
);

export default service;
